const selfWidget = this.widgetObj;
const helper = new Helper(this);
const prefix = helper.getVariable('environmentType');
// 基础服务
const basicRequest = BasicServices.getInstance(prefix);
// 流媒体服务
const streamRequest = StreamServices.getInstance(prefix);
// 应急服务
const emergencyRequest = EmergencyServices.getInstance(prefix);
// 物联 service
const iotServiceRequest = IotServiceServices.getInstance(prefix);
// 融合通讯
const communicateRequest = CommunicateServices.getInstance(prefix);


const tabs = {
    /**
     * 获取按钮组件
     *
     * @return {{all: *, offline: *, online: *}}
     */
    getAllBtn () {
        try {
            return [helper.get('org_btn'), helper.get('group_btn'), helper.get('device_btn')]
        } catch (e) {
            console.error(e);
        }

    },
    /**
     * 设置选中
     *
     * @param active
     */
    setActive(active) {
        $(active.__box).css("box-shadow", "inset 0 -5px 8px var(--active-color)");
    },

    /**
     * 取消选中
     *
     * @param unActive
     */
    setUnActive(unActive) {
        $(unActive.__box).css("box-shadow", "inset 0 0 5px var(--body-bg)");
    },

    /**
     * 选中对用按钮
     * 隐藏其他按钮
     *
     * @param widgetAliasName
     */
    active(widgetAliasName) {
        const allTabs = tabs.getAllBtn();
        allTabs.forEach(item => {
            if (item.base?.alias === widgetAliasName) {
                tabs.setActive(item)
            } else {
                tabs.setUnActive(item)
            }
        });
    },
}

const syTree = {
    /**
     * 获取搜索条件
     *
     * @return {*|string|jQuery}
     */
    getSearchText () {
        const searchInputWidget = helper.get('search_input');
        return $(searchInputWidget.__box).find('.input-filter').val();
    },
    /**
     * 获取选中状态
     * checkbox { 全部 | 在线 }
     *
     * @return {*}
     */
    getCheckedStatus () {
        const typeSelectWidget = helper.get('type_selection');
        return typeSelectWidget.widgetObj.getChecked()?.value;
    },
    /**
     * 重写调度台用户
     *
     * @param typeCode
     * @param communicationName
     * @param personName
     * @param username
     * @param userId
     * @return {string}
     */
    setTitle ({ typeCode, communicationName, personName, username, userId } = {}) {
        let title = '';

        if (typeCode === 'dispatchDesk') title += '调度台';

        title += (communicationName || username || personName);

        if (userId) title += `(${userId})`;

        return title
    },

    /**
     * 重写用户数据
     *
     * @param member
     * @param index
     * @return {*&{treeId: *, type: string, title: string, userId, username: string}}
     */
    resetMember (member, index) {
        return {
            ...member,
            type: '1',
            title: `${member.personName || member.communicationName || `匿名${index}`}(${member.account})`,
            username: `${member.personName || member.communicationName || `匿名${index}`}`,
            userId: member.account,
            treeId: member.id || member.personId,
        }
    },

    /**
     * 生成随机数
     *
     * @param num
     * @return {number}
     */
    random (num = 10) {
        return parseInt(Math.random() * Math.pow(10, num))
    },

    /**
     * 重组数据结构
     *
     * @param item
     * @return {*}
     */
    breakDataSource (item) {
        if(item.pointId || item.communicationName || item.personName) {
            item.id = item.personId;
            item.userId = item.account || item.communicationAccount;
            item.username = item.communicationName || item.personName;
            item.title = syTree.setTitle(item);
            item.treeId = item.userId;
            item.disabled = true
        } else if(item.orgId || item.orgName) {
            item.title = `${item.orgName}[${item.count}]`;
            item.id = item.orgId;
            item.treeId = item.orgId;
        } else if (item.deptId || item.deptName) {
            item.title = `${item.deptName}[${item.count}]`;
            item.id = item.deptId;
            item.treeId = item.deptId;
        } else if (item.distributionGroupId || item.distributionGroupName) {
            item.title = `${item.distributionGroupName}[${item.count}]`;
            item.id = item.distributionGroupId;
            item.treeId = item.distributionGroupId;
        } else if (item.equipmentTypeName || item.equipmentTypeCode) {
            item.title = `${item.equipmentTypeName}[${item.count}]`;
            item.id = item.equipmentTypeCode;
            item.treeId = item.equipmentTypeCode;
        }

        if (item.children) {
            item.type = '0'
            item.children = item.children.map(syTree.breakDataSource)
        }

        // 调度台
        const dispatchLength = item.dispatchList?.length
        if (dispatchLength) {
            const id = `${syTree.random(10)}-${syTree.random(10)}`;
            item.children.unshift({
                id,
                treeId: id,
                title: `调度台[${dispatchLength}]`,
                children: item.dispatchList.map(syTree.resetMember),
            })
        }

        // 组织机构
        if (item.orgList) item.children = item.orgList.map(syTree.breakDataSource)
        // 群组
        if (item.groupList) item.children = item.groupList.map(syTree.breakDataSource)
        // 用户列表
        if (item.personList) item.children = item.personList.map(syTree.breakDataSource)
        // 通讯账号
        if (item.accountData) item.children = item.accountData.map(syTree.breakDataSource)
        // 设备列表
        if (item.equipmentType) item.children = item.equipmentType.map(syTree.breakDataSource)

        return item
    },

    /**
     * 在 tree 没有加载时，使用此函数缓存树；
     * 在 tree 加载完成后，调用此函数重新渲染。
     */
    renderTreeSync(artemis) {},

    /**
     * 渲染树
     *
     * @param dataSource
     */
    renderTree (dataSource) {
        const three = helper.get('三维组件');
        // checkbox { 全部 | 在线 }
        const select = syTree.getCheckedStatus('search_input');
        const artemis = three?.widgetObj.artemis;
        const __renderTree = (artemis) => {
            let __data = dataSource.map(syTree.breakDataSource);
            if (select === 'all') {
                selfWidget._option.dataSource = artemis.resetUsersStatus(__data);
            } else {
                selfWidget._option.dataSource = artemis.filterUsersOnline(__data);
            }
        }

        if (artemis) {
            __renderTree(artemis)
        } else {
            syTree.renderTreeSync = __renderTree
        }
    },

    /**
     * 加载组织机构
     */
    loadOrgListData (params) {
        return communicateRequest.getOrgListByName(params).then((result) => {
            console.log('artemis: => ', artemis, result)
            if (Array.isArray(result)) return syTree.renderTree(result)
        })
    },

    /**
     * 加载群组
     */
    loadGroupListData (params) {
        return communicateRequest.getGroupListByName(params).then((result) => {
            console.log('artemis: => ', artemis, result)
            if (Array.isArray(result)) return syTree.renderTree(result)
        })
    },

    /**
     * 加载通讯账号
     */
    loadAccountListData (params) {
        return communicateRequest.getAllAccountByEquipment(params).then((result) => {
            console.log('artemis: => ', artemis, result)
            if (Array.isArray(result)) return syTree.renderTree(result)
        })
    },
}


console.log('页面初始化前: helper => ', helper)